package com.itheima.miankuangjia;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;

public class BeanFactory {
    public BeanFactory(){}
    private static HashMap<Object,Object> hm=new HashMap<>();
    static {
        try {
            //1.利用类加载器获取xml的真实路径再通过jsoup解析,解析之后拿到标签对象的集合
            ClassLoader classLoader = BeanFactory.class.getClassLoader();
            String path = classLoader.getResource("element.xml").getPath();
            Document parse = Jsoup.parse(new File(path), "UTF-8");
            Elements elements = parse.getElementsByTag("bean");
            //2.遍历标签对象集合拿到值,通过id和class值创建对象
            for (Element element : elements) {
                String idvalue = element.attr("id");
                String aClass = element.attr("class");
                Class<?> clazz = Class.forName(aClass);
                Constructor<?> con = clazz.getDeclaredConstructor();
                Object obj = con.newInstance();
                //3.拿到成员标签的对象并遍历取值
                Elements pro = element.getElementsByTag("property");
                for (Element element1 : pro) {
                    //拿到成员变量
                    String namevalue = element1.attr("name");
                    //拿到成员变量的值
                    String value = element1.attr("value");
                    //创建成员变量对象将类型返回为String
                    Field df = clazz.getDeclaredField(namevalue);
                    df.setAccessible(true);
                    Class<?> type = df.getType();
                    String typestring = type.toString();
                    if (typestring.contains("int")){
                        df.set(obj,Integer.parseInt(value));
                    }else {
                        df.set(obj,value);
                    }
                }
                hm.put(idvalue,obj);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Object GetObject(Object key){
        if (!hm.containsKey(key)){
            return "好好学习天天向上";
        }
        return hm.get(key);
    }
}
